package com.caowj.composedemo.composable

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import coil.annotation.ExperimentalCoilApi
import com.google.accompanist.insets.navigationBarsHeight
import com.google.accompanist.insets.statusBarsHeight
import com.google.accompanist.pager.ExperimentalPagerApi
import com.caowj.composedemo.widget.BottomNavBar
import com.caowj.composedemo.widget.KeyNavigationRoute
import com.caowj.composedemo.widget.Nav
import com.caowj.composedemo.widget.NavigationHost
import kotlinx.coroutines.launch

/**
 * <pre>
 *     通过Navigation导航展示新功能（只需要一个activity）
 *     参考：https://github.com/linxiangcheer/PlayAndroid
 *     作者：Caowj
 *     邮箱：caowj1104@163.com
 *     日期：2022/3/2 15:15
 * </pre>
 */
@ExperimentalCoilApi
@ExperimentalPagerApi
@Composable
fun MainCompose(
    navHostController: NavHostController = rememberNavController(),
    onFinish: () -> Unit
) {
    val scaffoldState = rememberScaffoldState()
    val scope = rememberCoroutineScope()

    //返回back堆栈的顶部条目
    val navBackStackEntry by navHostController.currentBackStackEntryAsState()
    //返回当前route
    val currentRoute = navBackStackEntry?.destination?.route ?: Nav.BottomNavScreen.HomeScreen.route

    //是否为route == "main",主页面的内容
    if (isMainScreen(currentRoute)) {
        Scaffold(
            scaffoldState = scaffoldState,
            drawerContent = {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(text = "抽屉组件中的内容")
                }
            },
            contentColor = MaterialTheme.colors.background,
            //标题栏区域
            topBar = {
                Column {
                    //内容不挡住状态栏 如果不设置颜色这里会自己适配，但可能产生闪烁
                    Spacer(
                        modifier = Modifier
                            .background(MaterialTheme.colors.primary)
                            .statusBarsHeight()
                            .fillMaxWidth()
                    )

                    MainTopBar(Nav.bottomNavRoute.value)
                }
            },
            floatingActionButtonPosition = FabPosition.End,
            //悬浮按钮
            floatingActionButton = {
                ExtendedFloatingActionButton(
                    text = { Text("Login") },
                    onClick = {
                        scope.launch {
//                        scaffoldState.snackbarHostState.showSnackbar("点击了悬浮按钮")
                            //跳转到登录页面
                            navHostController.navigate(KeyNavigationRoute.LOGIN.routeStr)
                        }
                    }
                )
            },
            //屏幕内容区域
            content = {
                //内容嵌套在Scaffold中
                NavigationHost(navHostController, it, onFinish)

                OnTwoBackContent(navHostController)
            },
            //底部导航栏
            bottomBar = {
                Column {
                    BottomNavBar(Nav.bottomNavRoute.value, navHostController)
                    //内容不挡住导航栏 如果不设置颜色这里会自己适配，但可能产生闪烁
                    Spacer(
                        modifier = Modifier
                            .background(MaterialTheme.colors.primary)
                            .navigationBarsHeight()
                            .fillMaxWidth()
                    )
                }
            }
        )
    } else {
        //独立页面
        NavigationHost(navHostController, onFinish = onFinish)
    }
}

/**
 * 主页面的标题栏
 */
@Composable
private fun MainTopBar(bottomNavScreen: Nav.BottomNavScreen) {
    com.caowj.composedemo.widget.AppBar(stringResource(bottomNavScreen.resourceId))
//    when (bottomNavScreen) {
//        //首页
//        Nav.BottomNavScreen.HomeScreen -> {
//            com.caowj.composedemo.widget.AppBar("首页")
//        }
//
//        //学习
//        Nav.BottomNavScreen.LearnScreen -> {
//            com.caowj.composedemo.widget.AppBar("学习")
//        }
//    }
}


/**
 * 在主界面点击两次返回按钮,返回到手机桌面,再重新打开app,此时显示退出时的主界面
 */
@Composable
private fun OnTwoBackContent(navHostController: NavHostController) {
    if (Nav.twoBackFinishActivity) {
        LaunchedEffect(Unit) {
            navHostController.navigate(Nav.bottomNavRoute.value.route) {
                popUpTo(navHostController.graph.findStartDestination().id) {
                    saveState = true
                }
                //避免重建
                launchSingleTop = true
                //重新选择以前选择的项目时，恢复状态
                restoreState = true
            }
            Nav.twoBackFinishActivity = false
        }
    }
}


/**
 * 是否是首页的内容
 */
fun isMainScreen(route: String): Boolean = when (route) {
    Nav.BottomNavScreen.HomeScreen.route,
//    Nav.BottomNavScreen.ProjectScreen.route,
//    Nav.BottomNavScreen.SquareScreen.route,
//    Nav.BottomNavScreen.PublicNumScreen.route,
    Nav.BottomNavScreen.LearnScreen.route,
//    Nav.BottomNavScreen.MineScreen.route
    -> true
    else -> false
}